package cn.scu.ne04jdemo.controller;

import cn.scu.ne04jdemo.entitiy.EarningRight;
import cn.scu.ne04jdemo.entitiy.OwnershipRight;
import cn.scu.ne04jdemo.service.EarningRightService;
import cn.scu.ne04jdemo.util.JsonResponse;
import cn.scu.ne04jdemo.util.PageUtil;
import com.alibaba.excel.EasyExcel;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@RestController
public class EarningRightController {
    private final EarningRightService earningRightService;

    public EarningRightController(EarningRightService earningRightService) {
        this.earningRightService = earningRightService;
    }

    @GetMapping("/earningRights")
    public ResponseEntity<JsonResponse> getEarningRight(@RequestParam Map<String, String> params) {
        List<EarningRight> earningRights = earningRightService.queryEarningRightByParam(params);
        int pageNum = Integer.parseInt(params.getOrDefault("pageNum", "1"));
        int pageSize = Integer.parseInt(params.getOrDefault("pageSize", "10"));
        int total = earningRights.size();
        return ResponseEntity.ok(JsonResponse.success(PageUtil.page(earningRights, pageNum, pageSize))
                .addOtherData("total", total));
    }

    @GetMapping("/earningRights/download")
    @ResponseBody
    public void download(@RequestParam Map<String, String> params, HttpServletResponse response) {
        List<EarningRight> earningRights = earningRightService.queryEarningRightByParam(params);
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("收益权元信息.xlsx", "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            EasyExcel.write(response.getOutputStream(), OwnershipRight.class).sheet().doWrite(earningRights);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
